#coding=utf-8
import wx,threading
from google_search import getrev
from pyExcelerator import *

class FetchThread(threading.Thread):
    
    def __init__(self, query, fn, window):
        threading.Thread.__init__(self)
        
        self.query = query
        self.fn = fn
        self.window = window
    
    def run(self):
    
        data = getrev(self.query, engine='com')
        data = [[i[1], i[0], i[2]] for i in data]
        wx.CallAfter(self.window.LogMessage, data)
        
        wb = Workbook()
        sheet = wb.add_sheet(self.query)
        header = ['title', 'url', 'summary']
        
        for i in range(len(header)):
            sheet.write(0, i, header[i])    
        for i in range(len(data)):
            items = data[i]
            for j in range(len(items)):
                sheet.write(i+1, j, items[j])    
        wb.save(self.fn)    
        
        wx.CallAfter(self.window.ThreadFinished)
        
class MainFrame(wx.Frame):
    
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Google Search', 
                size=(500, 350))
        panel = wx.Panel(self, -1)
        
        sizer = wx.GridBagSizer(hgap=5, vgap=5)
        
        self.st = wx.StaticText(panel, -1, label=u'Enter A Keyword:', 
                                style=wx.ALIGN_CENTER)
        sizer.Add(self.st, pos=(0, 0))
        
        self.tc = wx.TextCtrl(panel, -1, 
                size=(200, -1))
        self.tc.SetInsertionPoint(0)
        sizer.Add(self.tc, pos=(0, 1))
        
        self.bt = wx.Button(panel, -1, "go")
        self.Bind(wx.EVT_BUTTON, self.OnClick, self.bt)
        sizer.Add(self.bt, pos=(0, 2))
        
        self.mt = wx.TextCtrl(panel, -1,
                    size = (460, 300),
                    style=wx.TE_MULTILINE|wx.TE_READONLY)
        sizer.Add(self.mt, pos=(1, 0),span=(3,3) )
        
        panel.SetSizer(sizer)
       
    def LogMessage(self, msg):
        for data in msg:
            self.mt.AppendText('%s\n%s\n%s\n\n'%(data[0], data[1], data[2]))
            
        
    def ThreadFinished(self):
        message_dlg = wx.MessageDialog(None, "Success! Check the Excel file, please ",
                          'A Message Box',
                          wx.OK)
        message_dlg.ShowModal()
            
    def OnClick(self, event):
        
        dlg = wx.FileDialog(self, style=wx.SAVE,
                message="chose output Excel file")
                
        if dlg.ShowModal() == wx.ID_OK:
            fn = dlg.GetPath()
            if fn.split('.')[-1] != 'xls':
                fn = fn + '.xls'
            
            self.mt.Clear()
            query = self.tc.GetValue()
            query = query.strip()
            #print query
            
            ft = FetchThread(query, fn, self)
            ft.setDaemon(True)
            ft.start()
            
if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = MainFrame()
    frame.Show()
    app.MainLoop()
    
